package boot

import (
	"encoding/json"
	"flag"
	"github.com/spf13/viper"
	"github.com/wendy512/iec104/pkg/db"
	"github.com/wendy512/iec104/pkg/global"
	"github.com/wendy512/iec104/pkg/logger"
	"log"
)

func DoInit() {

	var configFileName string
	flag.StringVar(&configFileName, "config", "config", "config file name")
	flag.Parse()

	viper.SetConfigName(configFileName) // 设置配置文件的名字
	viper.AddConfigPath("./config")     // 添加配置文件所在的路径
	viper.SetConfigType("yml")          // 设置配置文件类型，可选

	log.Printf("read config file %s", configFileName)

	err := viper.ReadInConfig()
	if err != nil {
		log.Fatalf("Fail to parse 'config.yml': %v", err)
	}

	err = viper.Unmarshal(&global.Config)
	if err != nil {
		log.Fatalf("Fail to Unmarshal 'config.yml': %v", err)
	}

	// check config
	fieldHeadSet := make(map[string]bool)
	for _, readConfig := range global.Config.Read {
		if fieldHeadSet[readConfig.FieldHead] == true {
			logger.Fatalf("config", "fieldHead:%s is duplicate", readConfig.FieldHead)
		}
		fieldHeadSet[readConfig.FieldHead] = true
	}

	// set default
	if global.Config.ReadFreq == 0 {
		global.Config.ReadFreq = 1000
	}

	// init
	LoggerInit()

	// print config
	configBytes, _ := json.Marshal(global.Config)
	logger.Infof("config", "load file: config/%s.yml. info : %s", configFileName, string(configBytes))

	// db init
	db.IotDBInit()
}
